/**
 * 
 */
package com.autonavi.car.si.FileStore.task;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autonavi.car.si.FileStore.Config.FTPHostManager.FTPHost;
import com.autonavi.car.si.FileStore.Config.FileStoreConfig;
import com.autonavi.car.si.FileStore.model.FileVO;
import com.autonavi.car.si.FileStore.util.FtpUtil;

/**
 * 文件上传VO
 * 
 * @author kucheng.liao@autonavi.com
 * @date Nov 24, 2014
 * 
 */
public class FileTask extends Thread {

	private static Logger log = LoggerFactory.getLogger(FileTask.class);

	private BlockingQueue<FileVO> queue;

	public FileTask(BlockingQueue<FileVO> queue) {
		this.queue = queue;
	}

	public void run() {
		while (true) {
			excute();
		}

	}

	private void excute() {
		try {
			long time = 5000;
			int i = 0;
			while (true) {
				FileVO vo = queue.poll(time, TimeUnit.SECONDS);
				if (null != vo) {
					if (vo.getOperate() == FileVO.FileOperate.STOR) {
						executeUploadTask(vo);
						break;
					} else if (vo.getOperate() == FileVO.FileOperate.GET) {
						executeDownloadTask(vo);
						break;
					} else {
						log.warn("未知操作类型");
					}
				}
				i++;
				if (i < 50) {
					time = time << 1;
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
	}

	private void executeDownloadTask(FileVO vo) {
		try {
			FileStoreConfig config = FileStoreConfig.getInstance();

			List<FTPHost> hosts = config.getManager().getHostBySlice(vo.getSlice());
			if (null != hosts && hosts.size() > 0) {

				for (FTPHost host : hosts) {
					try {
						FtpUtil.download(host, vo);
						if(null!=vo.getIn()){
							vo.setStatus(200);
							return;
						}else{
							if(log.isWarnEnabled()){
								log.warn("下载文件失败 "+host.getRootPath()+"/"+vo.getStorePath()+"/"+vo.getUniqueFileName());
								log.warn("host:"+host);
							}
							vo.setStatus(500);
						}
					} catch (IOException e) {
                         log.error("HOST:+"+host+"下载数据出现IO异常，如果存在多个FTP节点，使用下个FTP节点下载数据", e);
					}
				}
			} else {
				log.error("can't find node for store data");
			}
		} catch (Exception e) {
			log.error("", e);
		}
		vo.setStatus(500);
	}

	/**
	 * 执行文件上传
	 * 
	 * @param vo
	 */
	private void executeUploadTask(FileVO vo) {
		try {
			FileStoreConfig config = FileStoreConfig.getInstance();
			// 通过UUID来实现数据唯一
			vo.setUniqueFileName(UUID.randomUUID().toString().replaceAll("-", ""));
			List<FTPHost> hosts = config.getManager().getHostByFileName(vo);
			if (null != hosts && hosts.size() > 0) {
				for (FTPHost host : hosts) {
					if (FtpUtil.upload(host, vo) != 200) {
						vo.setStatus(500);
						return;
					}
				}
				vo.setStatus(200);
				return;
			} else {
				log.error("can't find node for store data");
			}
		} catch (Exception e) {
			log.error("", e);
		}
		vo.setStatus(500);
	}

}
